import config from '@/utils/config.ts';
import toolLogin from '@/utils/login.js';

interface IReqOption {
	baseUrl?: string;
	url: string;
	header?: any;
	method: 'GET' | 'POST' | 'PUT' | 'DELETE';
	data: any;
}

interface IRespone {
	code: number;
	data: any;
	message: string;
	success: boolean;
}

export const request = (option: IReqOption): Promise<IRespone> => {
	if (!option.baseUrl) {
		option.baseUrl = config.baseUrl;
	}

	option.header = {
		token: ''
	};
	const token = uni.getStorageSync('token');
	option.header.token = token ?? '';

	if (process.env.NODE_ENV === 'development') {
		console.log('res-befor', option);
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${option.baseUrl}${option.url}`,
			header: option.header,
			method: option.method,
			data: option.data,
			success: (res) => {
				if (process.env.NODE_ENV === 'development') {
					console.log('res-after', res);
				}

				if (res.errMsg == 'request:fail timeout') {
					uni.showToast({
						icon: 'error',
						title: '网络不佳请刷新'
					});
					reject(res);
				}

				if (res.errMsg == 'request:fail ') {
					uni.showToast({
						icon: 'error',
						title: '请检查网络连接'
					});
					reject(res);
				}

				const response: IRespone = res.data as IRespone;
				if (response.code == 200) {
					resolve(res.data as IRespone);
				} else if (response.code == 401) {
					uni.setStorageSync('token', '');
					uni.showModal({
						title: '提示',
						content: '登录过期请重新登录',
						success: (res) => {
							if (res.confirm) {
								toolLogin.gotoLogin();

								uni.setStorageSync('userInfo', '{}');
							}
						}
					});

					reject(res);
				} else {
					console.error('请求失败', JSON.stringify(res));
					reject(res);
				}
			},
			fail: (err: UniApp.GeneralCallbackResult) => {
				const res: IRespone = {
					code: 0,
					data: '',
					message: err.errMsg,
					success: false
				};
				reject(res);
			},
			complete: () => {}
		});
	});
};
export default {};
